package com.example.httpstest;

import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpFactory {
	private static CookieStore CookieStore = null;
	public static DefaultHttpClient HttpClient = SSLSocketFactoryEx.getNewHttpClient();
	public static HttpContext context = new BasicHttpContext();

	private static void InItHttpClientSetting() {
		HttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000);
		HttpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	}

	public static String Request(String URL, List<NameValuePair> list, String resultKey) {

		String strRet = "";
		try {
			InItHttpClientSetting();
			HttpResponse response;
			HttpPost httpost = new HttpPost(URL);
			httpost.setHeader("Accept-Charset", "utf-8");
			httpost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
			/*
			 * if(CookieStore != null) HttpClient.setCookieStore(CookieStore);
			 */

			response = HttpClient.execute(httpost, context);

			HttpEntity entity = response.getEntity();
			if (response.getStatusLine().getStatusCode() == 200) {

				CookieStore = HttpClient.getCookieStore();
				Header header = response.getFirstHeader("Api-Key");
				if (header != null && header.getValue().equals("ok")) {
				} else {
					strRet = EntityUtils.toString(entity, "utf-8");
				}
			} else {
				String st = EntityUtils .toString(response.getEntity(), "GB2312");
				Log.w("404", st);
			}
			if (entity != null) {
				entity.consumeContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strRet;
	}
}
